package com.useeinfo.oa.open.dashboard.security;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.action.BaseAction;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Personnel;
import com.useeinfo.oa.modules.security.biz.SystemRoleBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.enums.OperationRoleEnum;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/web/admin/systemUser")
public class SystemUserAction extends BaseAction {

    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private SystemRoleBiz systemRoleBiz;
    @Autowired
    private HttpServletRequest httpServletRequest;

    // ******************************************************************************
    // ******************************* 代码自动生成开始 *******************************
    // ******************************************************************************

    /**
     * 打开列表页面
     */
    @RequestMapping("/getSystemUserListPage")
    public ModelAndView getSystemUserListPage() {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/system/systemUser/systemUserList");

        return modelAndView;
    }

    /**
     * 分页获取JSON数据
     */
    @RequestMapping("/getSystemUserListJSON")
    @ResponseBody
    public JSONObject getSystemUserListJSON(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                                            @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                                            @RequestParam(value = "orderBy", required = false) String orderBy,
                                            @RequestParam(value = "operationRoles", required = false) String operationRoles,
                                            @RequestParam(value = "searchCode", required = false) String searchCode) {

        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        queryParam.getSqlMap().put("searchCode", searchCode);
        queryParam.getSqlMap().put("operationRoles", operationRoles);
        if (StringUtils.isNotBlank(orderBy))
            queryParam.setSqlOrder("order by " + orderBy);
        return systemUserBiz.findJSONList(queryParam);
    }

    /**
     * 获取编辑页面
     */
    @RequestMapping("/getSystemUserEditPage")
    public ModelAndView getSystemUserEditPage(@RequestParam(value = "isPage", required = false) String isPageParam,
                                              @RequestParam(value = "userId", required = false) String userIdParam) {

        Long userId = StringConverters.ToLong(userIdParam);

        SystemUser systemUser = null;
        if (userId != null) {
            systemUser = systemUserBiz.findModel(userId);
        }
        if (systemUser == null && "1".equals(isPageParam)) {
            systemUser = systemUserBiz.getByUserAccount(userIdParam);
        }
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.setViewName("pages/system/systemUser/systemUserEditPart");
        modelAndView.addObject("systemUser", systemUser);
        return modelAndView;
    }

    /**
     * 获取编辑页面
     */
    @RequestMapping("/getSystemUserEditPageEnter")
    public ModelAndView getSystemUserEditPageEnter(@RequestParam(value = "isPage", required = false) String isPageParam,
                                                   @RequestParam(value = "userId", required = false) String userIdParam) {

        Long userId = StringConverters.ToLong(userIdParam);

        SystemUser systemUser = null;
        if (userId != null) {
            systemUser = systemUserBiz.findModel(userId);
        }
        if (systemUser == null && "1".equals(isPageParam)) {
            systemUser = systemUserBiz.getByUserAccount(userIdParam);
        }
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.setViewName("pages/system/systemUser/systemUserEditPartEnter");
        modelAndView.addObject("systemUser", systemUser);
        modelAndView.addObject("systemRole", systemRoleBiz.findList());
        return modelAndView;
    }

    /**
     * 获取详情页面
     */
    @RequestMapping("/getSystemUserViewPage")
    public ModelAndView getSystemUserViewPage(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (systemUser == null) {
            modelAndView.setViewName("redirect:/security/loginout.action");
            return modelAndView;
        }
        modelAndView.setViewName("pages/system/systemUser/systemUserViewPart");
        modelAndView.addObject("systemUser", systemUser);
        return modelAndView;
    }

    /**
     * 修改密码
     */
    @RequestMapping("/updataPassward")
    public ModelAndView updataPassward(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (systemUser == null) {
            modelAndView.setViewName("redirect:/security/loginout.action");
            return modelAndView;
        }
        modelAndView.setViewName("pages/system/systemUser/updatePassward");
        modelAndView.addObject("systemUser", systemUser);
        return modelAndView;
    }

    /**
     * 执行提交的新增或修改请求
     */
    @RequestMapping("/executeSystemUserEdit")
    @ResponseBody
    public ResultDto executeSystemUserEdit(@RequestParam(value = "id", required = false) String id,
                                           @RequestParam(value = "userAccount", required = false) String userAccount,
                                           @RequestParam(value = "userName", required = false) String userName,
                                           @RequestParam(value = "operationRole", required = false) String operationRole,
                                           @RequestParam(value = "enterpriseData", required = false) List<String> enterpriseData) {
        SystemUser systemUser = systemUserBiz.findModel(StringConverters.ToLong(id));
        if (systemUser == null) {
            systemUser = new SystemUser();
        }
        systemUser.setUserAccount(userAccount);
        systemUser.setUserName(userName);
        //判断用户名是否重复
        if (systemUserBiz.existUserAccount(systemUser)) {
            return ResultUtil.error("您输入的用户名为空或已存在，请重新输入");
        }
        //新增企业、平台管理员，密码默认
        if (systemUser.getId() == null) {
            systemUser.setUserPassword(Configuration.getConfigurationByName("defaultPassword"));
        }
        if (StringUtils.isBlank(operationRole)) {
            return ResultUtil.error("请选择账号类型！");
        }
        if (OperationRoleEnum.admin.getCode().equals(operationRole)) {
            systemUser.setOperationRole(OperationRoleEnum.admin.getCode());
            systemUserBiz.addOrUpdate(systemUser);
            systemUserBiz.removeEnterprise(systemUser.getId());
        } else if (OperationRoleEnum.enterprise.getCode().equals(operationRole)) {
            if (CollectionUtils.isEmpty(enterpriseData)) {
                return ResultUtil.error("请选择企业！");
            }
            systemUser.setOperationRole(OperationRoleEnum.enterprise.getCode());
            if (systemUser.getId() != null) {
                //将所有的公司删除，将现在的公司加上
                systemUserBiz.removeEnterprise(systemUser.getId());
            }
            systemUserBiz.addOrUpdate(systemUser);
            systemUserBiz.addEnterprise(systemUser.getId(), enterpriseData);
        }
        return ResultUtil.success();
    }

    /**
     * 修改密码
     */
    @RequestMapping("/updateSystemUserPassward")
    @ResponseBody
    public ResultDto updateSystemUserPassward(@RequestParam(value = "id", required = false) String id,
                                              @RequestParam(value = "old_password", required = false) String old_password,
                                              @RequestParam(value = "password", required = false) String password,
                                              @RequestParam(value = "confirmPassword", required = false) String confirmPassword) {

        SystemUser systemUser = systemUserBiz.findModel(StringConverters.ToLong(id));
        if (systemUser == null) {
            return ResultUtil.error("用户不存在！");
        }
        if (StringUtils.isBlank(old_password) || StringUtils.isBlank(password) || StringUtils.isBlank(confirmPassword) || !old_password.equals(systemUser.getUserPassword())) {
            return ResultUtil.error("密码不正确！");
        }
        if (!password.equals(confirmPassword)) {
            return ResultUtil.error("新密码与确认新密码不同！");
        }
        systemUser.setUserPassword(password);
        systemUserBiz.addOrUpdate(systemUser);
        return ResultUtil.success();
    }

    /**
     * 逻辑删除机构用户信息
     */
    @RequestMapping("/logicRemoveSystemUser")
    @ResponseBody
    public ResultDto logicRemoveSystemUser(@RequestParam(value = "userId", required = false) String userIdParam,
                                           @RequestParam(value = "isFakeDelete", required = false) String isFakeDelete) {

        Long userId = StringConverters.ToLong(userIdParam);

        if ("1".equals(isFakeDelete)) {
            systemUserBiz.delete(userId);
        } else {
            systemUserBiz.logicRemove(userId);
        }

        return ResultUtil.success();
    }

    /**
     * 获取用户-选择框
     */
    @RequestMapping("/getUserListMagic")
    @ResponseBody
    public List<SelectVO> getSystemRoleListMagic(@RequestParam(value = "q", required = false) String q,
                                                 @RequestParam(value = "id", required = false) String id) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        List<SelectVO> selectVOS = new ArrayList<>();
        SystemUser user = systemUserBiz.findModel(StringConverters.ToLong(id));
        if (user != null) {
            selectVOS.add(new SelectVO(user.getUserName(), user.getId() + ""));
        }
        QueryParam queryParam = new QueryParam(1, 20);
        queryParam.getSqlMap().put("magicLike", q);
        queryParam.getSqlMap().put("magicId", id);
        queryParam.getSqlMap().put("enterpriseIds",StringConverters.null2String(enterprise.getId()));
        List<SystemUser> systemUsers = systemUserBiz.findList(queryParam);
        systemUsers.forEach(systemUser -> selectVOS.add(new SelectVO(systemUser.getUserName(), systemUser.getId() + "")));
        return selectVOS;
    }

    // ******************************************************************************
    // ******************************* 代码自动生成结束 *******************************
    // ******************************************************************************


    /**
     * 根据账号查人
     *
     * @return
     */
    @RequestMapping("/findUserByAccount")
    @ResponseBody
    public ResultDto findUserByAccount(String account) {
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("userAccount", account);
        List<SystemUser> systemUsers = systemUserBiz.findList(queryParam);
        if (CollectionUtils.isNotEmpty(systemUsers)) {
            SystemUser systemUser = systemUsers.get(0);
            return ResultUtil.success(systemUser.toJSONObject());
        }
        return ResultUtil.error();
    }

    /**
     * 获取企业用户的所属企业
     */
    @RequestMapping("/getUserEnterPrise")
    @ResponseBody
    public ResultDto getUserEnterPrise(@RequestParam(value = "id", required = false) String id) {

        SystemUser systemUser = systemUserBiz.findModel(StringConverters.ToLong(id));
        if (systemUser == null) {
            return ResultUtil.error("用户不存在！");
        }
        Set<Enterprise> enterpriseSet = systemUser.getEnterpriseSet();
        JSONArray rows = new JSONArray();
        enterpriseSet.forEach(enterprise -> rows.add(enterprise.getId()));
        return ResultUtil.success(rows);
    }


    /**
     * 当前登录用户重新授权的方法
     */
    public void reloadUserAuthority() {

        // 新的权限
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(new String[]{"从数据库中查询出来"});

        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        //principal.setAuthorities(authorityList);

        // 重新new一个token，因为Authentication中的权限是不可变的.
        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
                principal, authentication.getCredentials(),
                authorityList);
        result.setDetails(authentication.getDetails());
        securityContext.setAuthentication(result);
    }

    /**
     * 获取用户-选择框
     */
    @RequestMapping("/getUserList")
    @ResponseBody
    public List<SelectVO> getUserList(@RequestParam(value = "q", required = false) String q,
                                      @RequestParam(value = "id", required = false) String id,
                                      @RequestParam(value = "organizationId", required = false) String organizationId
    ) {
        List<SelectVO> selectVOS = new ArrayList<>();
        SystemUser user = systemUserBiz.findModel(StringConverters.ToLong(id));
        if (user != null) {
            selectVOS.add(new SelectVO(user.getUserName(), user.getId() + ""));
        }
        if (organizationId == null) {
            return selectVOS;
        }
        return systemUserBiz.getSystemUserByOrgan(organizationId);
    }
}